<template>
  <el-dialog v-model="isTransfer" :width="800" center :show-close="false">
    <template #header>
      <title-view title="列表字段设置" />
    </template>
    <div class="transfer-container" v-loading="isLoading">
      <div class="check-container">
        <div class="check-all-container">
          <el-checkbox v-model="isLeftCheckedAll" :indeterminate="isLeftIndeterminate" @change="handelLeftCheckedAll"
            >可选字段</el-checkbox
          >
        </div>
        <div class="list-container">
          <div class="search-box">
            <el-input v-model="searchVal" placeholder="请输入关键词" :suffix-icon="Search" @change="handleLeftSearch"> </el-input>
          </div>
          <template v-if="leftList.length">
            <div class="left-list-content">
              <div class="list-container-item" :class="{ 'item-active': item.checked }" v-for="item in leftList">
                <el-checkbox
                  v-model="item.checked"
                  :label="item.title"
                  :value="item.fieldId"
                  :key="item.fieldId"
                  @change="handleLeftChecked($event, item)"
                >
                  {{ item.title }}
                </el-checkbox>
              </div>
            </div>
          </template>
          <el-empty v-else />
        </div>
      </div>
      <div class="center-buttons">
        <el-button @click="handelTransferShow" :disabled="!leftSelected.length"
          >显示<el-icon><ArrowRightBold /></el-icon>
        </el-button>
        <el-button @click="handelTransferHide" :disabled="!rightSelected.length"
          >隐藏<el-icon><ArrowLeftBold /></el-icon
        ></el-button>
      </div>
      <div class="check-container">
        <div class="check-all-container">
          <el-checkbox v-model="isRightCheckedAll" :indeterminate="isRightIndeterminate" @change="handelRightCheckedAll"
            >已选字段</el-checkbox
          >
        </div>
        <div class="list-container">
          <VueDraggableNext
            v-if="rightList.length"
            class="dragArea"
            id="tabsContainer"
            v-model="rightList"
            chosenClass="chosenClass"
            :animation="500"
            :capture="true"
            handle=".drag-handle"
            :move="onMoveRight"
          >
            <div class="list-container-item" :class="{ 'item-active': item.checked }" v-for="item in rightList">
              <el-checkbox
                v-model="item.checked"
                :disabled="!item.isOperate"
                :label="item.title"
                :value="item.fieldId"
                :key="item.fieldId"
                @change="handleRightChecked($event, item)"
              >
                {{ item.title }}
              </el-checkbox>
              <img v-show="item.isOperate" class="drag-handle" :src="require('@/assets/images/image/drag-handle.png')" />
            </div>
          </VueDraggableNext>
          <el-empty v-else />
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handelCancel">取消</el-button>
        <el-button type="primary" @click="handelConfirm"> 确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, ref, getCurrentInstance } from "vue";
import _ from "lodash";
import { VueDraggableNext } from "vue-draggable-next";
import { ArrowLeftBold, ArrowRightBold, Search } from "@element-plus/icons-vue";
import { tableHeaderSortData, tableHeaderSort } from "@/apis/clientManager";

const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["update:modelValue", "transferConfirm"]);
const isTransfer = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});

const cloneLeftList = ref([]);
const isLoading = ref(false);
const getTableHeaderSort = async () => {
  try {
    isLoading.value = true;
    const {
      data: { notSelect, select }
    } = await tableHeaderSortData();
    leftList.value = notSelect || [];
    cloneLeftList.value = _.cloneDeep(notSelect);
    rightList.value = select || [];
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
  }
};

const isLeftCheckedAll = ref(false);
const isLeftIndeterminate = ref(false);
const leftList = ref([]);
const leftSelected = ref([]);
const handelLeftCheckedAll = e => {
  isLeftIndeterminate.value = e && false;
  leftList.value.forEach(item => {
    item.checked = e;
  });
  leftSelected.value = e ? _.cloneDeep(leftList.value) : [];
};
const handleLeftChecked = (e, data) => {
  if (e) {
    const isCheckedAll = leftList.value.every(item => item.checked);
    isLeftIndeterminate.value = !isCheckedAll;
    isLeftCheckedAll.value = isCheckedAll;
    //isCheckedAll:仅针对于搜索结果全选
    if (isCheckedAll) {
      if (leftList.value.length == cloneLeftList.value.length) {
        // 所有列表全选
        leftSelected.value = _.cloneDeep(leftList.value);
      } else {
        //所有列表未全选
        leftSelected.value.push(_.cloneDeep(data));
      }
    } else {
      leftSelected.value.push(_.cloneDeep(data));
    }
  } else {
    isLeftIndeterminate.value = leftList.value.some(item => item.checked);
    isLeftCheckedAll.value = false;
    const dataIndex = leftSelected.value.findIndex(item => item.fieldId === data.fieldId);
    dataIndex !== -1 && leftSelected.value.splice(dataIndex, 1);
  }
};
//搜索
const searchVal = ref("");
const handleLeftSearch = () => {
  const currentSearchVal = searchVal.value.trim();
  if (currentSearchVal) {
    leftList.value = cloneLeftList.value.filter(item => item.title.includes(currentSearchVal));
  } else {
    leftList.value = cloneLeftList.value;
  }
};

const isRightCheckedAll = ref(false);
const isRightIndeterminate = ref(false);
const rightList = ref([]);
const rightSelected = ref([]);
const handelRightCheckedAll = e => {
  isRightIndeterminate.value = e && false;
  rightList.value.forEach(item => {
    item.checked = item.isOperate ? e : false;
  });
  rightSelected.value = e ? _.cloneDeep(rightList.value).filter(item => item.checked) : [];
};
const handleRightChecked = (e, data) => {
  if (e) {
    const isOperates = rightList.value.filter(item => item.isOperate);
    const isCheckedAll = isOperates.every(item => item.checked);
    isRightIndeterminate.value = !isCheckedAll;
    isRightCheckedAll.value = isCheckedAll;
    if (isCheckedAll) {
      rightSelected.value = _.cloneDeep(isOperates);
    } else {
      rightSelected.value.push(_.cloneDeep(data));
    }
  } else {
    isRightIndeterminate.value = rightList.value.some(item => item.checked);
    isRightCheckedAll.value = false;
    const dataIndex = rightSelected.value.findIndex(item => item.fieldId === data.fieldId);
    dataIndex !== -1 && rightSelected.value.splice(dataIndex, 1);
  }
};
const onMoveRight = e => {
  return ![0].includes(e.relatedContext.index);
};

const handelTransferShow = () => {
  const listData = _.cloneDeep(leftSelected.value).map(item => {
    item.checked = false;
    return item;
  });
  rightList.value = [...rightList.value, ...listData];
  leftSelected.value = [];
  isLeftCheckedAll.value = false;
  isLeftIndeterminate.value = false;
  if (listData.length === leftList.value.length) {
    leftList.value = [];
  } else {
    leftList.value = leftList.value.filter(item => !listData.some(listItem => listItem.fieldId === item.fieldId));
  }

  cloneLeftList.value = cloneLeftList.value.filter(item => !listData.some(listItem => listItem.fieldId === item.fieldId));
  searchVal.value = "";
  handleLeftSearch();
};
const handelTransferHide = () => {
  const listData = _.cloneDeep(rightSelected.value).map(item => {
    item.checked = false;
    return item;
  });
  leftList.value = [...leftList.value, ...listData];
  rightSelected.value = [];
  isRightCheckedAll.value = false;
  isRightIndeterminate.value = false;
  if (listData.length === rightList.value.length) {
    rightList.value = [];
  } else {
    rightList.value = rightList.value.filter(item => !listData.some(listItem => listItem.fieldId === item.fieldId));
  }
  cloneLeftList.value = [...cloneLeftList.value, ...listData];
  searchVal.value = "";
  handleLeftSearch();
};

const handelConfirm = async () => {
  // emit("transferConfirm", { list: rightList.value });
  try {
    isLoading.value = true;
    const ids = rightList.value.map(item => item.fieldId);
    await tableHeaderSort({ fieldList: ids });
    isLoading.value = false;
    proxy.$modal.msgSuccess("保存成功");
    emit("transferConfirm");
  } catch (err) {
    isLoading.value = false;
  }
};
const handelCancel = () => {
  isTransfer.value = false;
};

getTableHeaderSort();
</script>

<style scoped lang="scss">
@use "transfer";
</style>
